package com.lagou.rpc.consumer.processor;

import com.lagou.rpc.consumer.anno.RpcReference;
import com.lagou.rpc.consumer.proxy.RpcClientProxy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * 在业务bean初始化以前进行处理
 *         给被@RpcReference注解修饰的成员重新赋值为代理后的对象
 */
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

    @Autowired
    private RpcClientProxy rpcClientProxy;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return null;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> aClass = bean.getClass();
        //获取类中所有声明的字段（包含public、private和protected）
        Field[] declaredFields = aClass.getDeclaredFields();
        for(Field field:declaredFields){
            if(field.getAnnotation(RpcReference.class) == null){
                continue;
            }
            //field.getType()  返回的是由该field标识的class对象   也就是IUserService的class对象
            Object proxy = rpcClientProxy.createProxy(field.getType());
            try{
                field.setAccessible(true);
                /**
                 * @RpcReference
                 * private UserService userService;
                 *      field.set(bean,proxy)  表示向UserService中重新赋值 被代理后的对象proxy
                 */
                field.set(bean,proxy);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return bean;
    }
}
